<template>
  <div>
    <!-- pdf预览 -->
    <div class="pdf-container" ref="pdfContainerRef">
      <canvas v-for="pageIndex in pdfPages" :id="`pdf-canvas-${pageIndex}`" :key="pageIndex" />
      <div class="sign-btn">
        <button v-if="!pdfUrl" :class="['sign-button', { disabled: isDisabled }]" @click="handleSign"> {{ buttonText }}
        </button>
        <button v-else class="confirm-button" @click="handleConfirm">确认</button>
      </div>
    </div>
  </div>
  <OverlayModal v-model="isModalVisible" @confirm="getPngUrl" />
</template>

<script setup lang="ts">
/* eslint-disable */
import { ref, onMounted, nextTick, computed } from "vue";
import * as PDFJS from "pdfjs-dist";

import * as PdfWorker from "pdfjs-dist/build/pdf.worker.js";
// import PdfBook from "../../../public/contract.pdf";
import OverlayModal from "../../components/OverlayModal.vue";

import { PDFDocument } from "pdf-lib";

import * as api from '../../api/index';
window.pdfjsWorker = PdfWorker;

const isModalVisible = ref(false);

const query = Object.fromEntries(new URL(window.location.href).searchParams);
const id = query.id;


let pdfDoc: any = null;
const pdfPages = ref(0);
const pdfScale = ref(1.5);
const pdfContainerRef = ref<HTMLElement | null>(null);

const pdfFileUrl: any = ref(null)


const isDisabled = ref(true)
const countdown = ref(5); // 倒计时秒数


// 签名

const pdfUrl = ref<string | null>(null)

const getPngUrl = (url: any) => {
  addImageToPdf(url)
}

const loadFile = (url: any) => {
  // 设定pdfjs的 workerSrc 参数
  PDFJS.GlobalWorkerOptions.workerSrc = PdfWorker;
  const loadingTask = PDFJS.getDocument(url);
  loadingTask.promise
    .then(async (pdf: any) => {
      pdf.loadingParams.disableAutoFetch = true;
      pdf.loadingParams.disableStream = true;
      pdfDoc = pdf; // 保存加载的pdf文件流
      pdfPages.value = pdfDoc.numPages; // 获取pdf文件的总页数
      await nextTick(() => {
        renderPage(1); // 将pdf文件内容渲染到canvas
      });
    })
    .catch((error: any) => {
      console.warn(`[upthen] pdfReader loadFile error: ${error}`);
    });
};

const renderPage = (num: any) => {
  pdfDoc.getPage(num).then((page: any) => {
    page.cleanup();
    if (pdfContainerRef.value) {
      pdfScale.value = pdfContainerRef.value.clientWidth / page.view[2];
    }
    const canvas: any = document.getElementById(`pdf-canvas-${num}`);
    if (canvas) {
      const ctx = canvas.getContext("2d");
      const dpr = window.devicePixelRatio || 1;
      const bsr =
        ctx.webkitBackingStorePixelRatio ||
        ctx.mozBackingStorePixelRatio ||
        ctx.msBackingStorePixelRatio ||
        ctx.oBackingStorePixelRatio ||
        ctx.backingStorePixelRatio ||
        1;
      const ratio = dpr / bsr;
      const viewport = page.getViewport({ scale: pdfScale.value });
      canvas.width = viewport.width * ratio;
      canvas.height = viewport.height * ratio;
      canvas.style.width = viewport.width + "px";
      canvas.style.height = viewport.height + "px";

      ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
      const renderContext = {
        canvasContext: ctx,
        viewport: viewport,
      };
      page.render(renderContext);
      if (num < pdfPages.value) {
        renderPage(num + 1);
      }
    }
  });
}

// 签名
const handleSign = () => {
  if (!isDisabled.value) {
    isModalVisible.value = true;
  }

}

// 从项目目录加载 PDF 文件
const loadPdfFromFile = async (pngUrl: any) => {
  // 测试数据
  // const response = await fetch(PdfBook);  // 假设 PDF 文件在 public/files 目录中
  const response = await fetch(pdfFileUrl.value);  // 假设 PDF 文件在 public/files 目录中

  const pdfBytes = await response.arrayBuffer();
  return pdfBytes;
};

// 添加图片到上传的 PDF 最后一页
const addImageToPdf = async (pngUrl: any) => {
  const pdfBytes1 = await loadPdfFromFile(pngUrl);

  // 加载上传的 PDF
  const pdfDoc = await PDFDocument.load(pdfBytes1);

  // 获取最后一页
  const pages = pdfDoc.getPages();
  const lastPage = pages[pages.length - 1];

  // 获取页面的尺寸
  // const { width, height } = lastPage.getSize();

  // 将 Base64 图片转换为 PDF 可用的图像格式
  const imageBytes = await fetch(pngUrl).then((res) => res.arrayBuffer());
  const image = await pdfDoc.embedPng(imageBytes);

  // 图片的尺寸
  const imageWidth = 140;
  const imageHeight = 60;

  // 在最后一页的指定位置添加图片
  lastPage.drawImage(image, {
    x: 100,  // 中心对齐
    y: 160,  // 图片位置
    width: imageWidth,
    height: imageHeight,
  });

  // 保存 PDF 并生成 URL
  const pdfBytes = await pdfDoc.save();
  const blob = new Blob([pdfBytes], { type: "application/pdf" });
  const url = URL.createObjectURL(blob);
  pdfUrl.value = url;
  loadFile(url)
};

const convertPdfUrlToBlob = async (pdfUrl: string): Promise<Blob> => {
  // 使用 fetch 获取 Blob 数据
  const response = await fetch(pdfUrl);
  if (!response.ok) {
    throw new Error("Failed to fetch PDF URL");
  }
  const blob = await response.blob(); // 转换为 Blob 数据
  return blob;
};

const convertPdfUrlToFile = async (pdfUrl: string, fileName: string): Promise<File> => {
  const blob = await convertPdfUrlToBlob(pdfUrl);
  return new File([blob], fileName, { type: blob.type });
};

const handleConfirm = () => {
  if (pdfUrl.value) {

    convertPdfUrlToFile(pdfUrl.value, 'signedContract.pdf').then((file: any) => {
      api.uploadFile({ file }).then(async (res: any) => {
        await api.confirm({ id: id, contractResult: res.url })
        window.location.href = './detail.html?id=' + id;
      })
    })

  }
}

// 倒计时逻辑
const startCountdown = () => {
  const interval = setInterval(() => {
    countdown.value -= 1;
    if (countdown.value <= 0) {
      clearInterval(interval);
      isDisabled.value = false; // 倒计时结束，设置为可点击
    }
  }, 1000);
};

const buttonText = computed(() =>
  isDisabled.value ? `我已知晓，去签名(${countdown.value}s)` : "我已知晓，去签名"
)

onMounted(() => {
  if (!id) {
    alert('无效的链接');
  }
  startCountdown()
  api.getResult(id).then((res: any) => {
    pdfFileUrl.value = res.data.contractModel
    loadFile(res.data.contractModel);
    // 测试数据    
    // loadFile(PdfBook)
  });
});
</script>

<style scoped lang="less">
.pdf-container {
  height: 100%;
  overflow-y: scroll;
  overflow-x: hidden;
  background: #fff;

  canvas {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .sign-btn {
    border-top: 1px dashed rgb(239, 239, 239);
    margin-bottom: 20px;
    padding: 10px 20px;
    text-align: right;


    .confirm-button {
      border: none;
      background: #1875FE;
      color: #fff;
      padding: 10px 14px;
      border-radius: 10px;
      min-width: 140px;
    }

    .sign-button {
      border: 1px solid #1875FE;
      background: #fff;
      color: #1875FE;
      padding: 10px 14px;
      border-radius: 10px;
      min-width: 140px;
    }

    .sign-button.disabled {
      background-color: rgba(0, 0, 0, 0.04);
      border-color: #d9d9d9;
      color: rgba(0, 0, 0, 0.25);
      cursor: not-allowed;
    }

    // .sign-button:not(.disabled):hover {
    //   border: 1px solid #1875FE;
    //   background: #fff;
    //   color: #1875FE;
    // }
  }
}
</style>
